package org.jypj.dev.util;

import net.sf.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {

    /**
     * 通过HttpURLConnection模拟post表单提交
     *
     * @param path
     * @param params 例如"name=zhangsan&age=21"
     * @return 数据结果字符串 可以是xml json html 等
     * @throws Exception
     */
    public static String sendPostRequestByForm(String path, String params) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");// 提交模式
        conn.setRequestProperty("token", "");
        conn.setConnectTimeout(5000);//连接超时 单位毫秒
        // conn.setReadTimeout(2000);//读取超时 单位毫秒
        conn.setDoOutput(true);// 是否输入参数
        byte[] bypes = params.toString().getBytes("UTF-8");
        conn.getOutputStream().write(bypes);// 输入参数
        InputStream inStream = conn.getInputStream();
        byte[] data = StreamTool.readInputStream(inStream);
        String text = new String(data, "UTF-8");
        return text;
    }

    /**
     * 通过HttpURlConnection模拟get请求
     *
     * @param path
     * @return 数据结果字符串 可以是xml json html 等
     * @throws Exception
     */
    public static String sendGetRequestForService(String path) throws Exception {
        URL url = new URL(path);
        System.out.println(url.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestProperty("Authorization", "Bearer YWMtCfz9Fh3LEee-flHV999EdgAAAAAAAAAAAAAAAAAAAAF0F3KQEooR55VGOyVYV8aOAgMAAAFbVxCMywBPGgAXlouuHrOfzhSp2mlA7UB5GjEGAKVStW4nm_4U6cxelQ");
        conn.setRequestMethod("GET");
        InputStream inStream = conn.getInputStream();
        byte[] data = StreamTool.readInputStream(inStream);
        String text = new String(data, "UTF-8");
        return text;
    }

    /**
     * 通过HttpURlConnection模拟put请求
     *
     * @param path
     * @return 数据结果字符串 可以是xml json html 等
     * @throws Exception
     */
    public static String sendPutRequestForService(String path, String params) throws Exception {
        URL url = new URL(path);
        System.out.println(url.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestProperty("Authorization", "Bearer YWMtCfz9Fh3LEee-flHV999EdgAAAAAAAAAAAAAAAAAAAAF0F3KQEooR55VGOyVYV8aOAgMAAAFbVxCMywBPGgAXlouuHrOfzhSp2mlA7UB5GjEGAKVStW4nm_4U6cxelQ");
        conn.setRequestMethod("PUT");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        //写入请求参数
        //这里要注意的是，在构造JSON字符串的时候，实践证明，最好不要使用单引号，而是用“\”进行转义，否则会报错
        // 关于这一点在上面给出的参考文章里面有说明
        dos.writeBytes(params);
        dos.flush();
        dos.close();
        InputStream inStream = conn.getInputStream();
        byte[] data = StreamTool.readInputStream(inStream);
        String text = new String(data, "UTF-8");
        return text;
    }

    /**
     * 发起https请求并获取结果
     *
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr 提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr){
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new TrustManager(){} };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            // if ("GET".equalsIgnoreCase(requestMethod))
            httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            System.out.println(ce);
        } catch (Exception e) {
            System.out.println(e);
        }
        return jsonObject;
    }
}